﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace LockDemo
{
    class ThreadTest
    {
        private int i = 0;
        public void Test()
        {
            Thread t1 = new Thread(Thread1);
            Thread t2 = new Thread(Thread2);
            t1.Start();
            t2.Start();
        }
        public void Thread1()
        {
            lock (this)
            {
                Console.WriteLine(this.i);
                Thread.Sleep(1000);
                Console.WriteLine(this.i);
            }
        }
        public void Thread2()
        {
            Thread.Sleep(500);
            this.i = 1;
            Console.WriteLine("Change the value in locking");
        }
    }
    public class ThreadTest2
    {
        private int i = 0;
        public void Test()
        {
            Thread t1 = new Thread(Thread1);
            Thread t2 = new Thread(Thread2);
            t1.Start();
            t2.Start();
        }
        public void Thread1()
        {
            lock (this)
            {
                Console.WriteLine(this.i);
                Thread.Sleep(1000);
                Console.WriteLine(this.i);
            }
        }
        public void Thread2()
        {
            lock (this)
            {
                Thread.Sleep(500);
                this.i = 1;
                Console.WriteLine("Can't change the value in locking");
                Console.WriteLine(this.i);
            }
        }
    }
    public class ThreadMain
    {
        public static void Main55()
        {
            //ThreadTest b = new ThreadTest();  
            //Thread t = new Thread(new ThreadStart(b.Test));  
            //t.Start();  

            ThreadTest2 b2 = new ThreadTest2();
            Thread t2 = new Thread(new ThreadStart(b2.Test));
            t2.Start();
            Console.Read();
        }
    }
}
